async function testNormalRequest() { await runTest('/api/normal', 10); }
async function testRateLimiting() { await runTest('/api/limit', 20); }
async function testConcurrencyIsolation() { await runTest('/api/isolation', 20); }
async function testHotspotProtection() { await runTest('/api/hotspot?param=value1', 20); }
async function testCircuitBreaker() { await runTest('/api/breaker', 20); }

async function runTest(apiUrl, requestCount) {
    clearConsole();
    const requests = Array.from({ length: requestCount }, () => sendRequest(apiUrl));
    await Promise.all(requests);
}

function clearConsole() {
    document.getElementById('console').innerHTML = '';
}

async function sendRequest(url) {
    const consoleDiv = document.getElementById('console');
    const message = createMessageElement(url);

    try {
        const response = await fetch(url, { method: 'GET' });
        if (!response.ok) {
          const text = await response.text();
          throw new Error(`HTTP ${response.status} - ${text}`);
        }

        const result = await response.json();
        updateMessage(message, JSON.stringify(result), 'success');
    } catch (error) {
        updateMessage(message, error.message || '未知错误', 'error');
    }
}

function createMessageElement(url) {
    const message = document.createElement('div');
    message.className = 'message';

    const leftPart = document.createElement('div');
    leftPart.className = 'left';
    leftPart.textContent = url;
    message.appendChild(leftPart);

    const rightPart = document.createElement('div');
    rightPart.className = 'right';
    message.appendChild(rightPart);

    const progressBarContainer = createProgressBar();
    rightPart.appendChild(progressBarContainer);

    document.getElementById('console').appendChild(message);
    return message;
}

function createProgressBar() {
    const progressBarContainer = document.createElement('div');
    progressBarContainer.className = 'pro-bar-container color-belize-hole';

    const progressBar = document.createElement('div');
    progressBar.className = 'pro-bar bar-100 color-peter-river';
    progressBar.setAttribute('data-pro-bar-percent', '100');

    const progressBarCandy = document.createElement('div');
    progressBarCandy.className = 'pro-bar-candy candy-ltr';
    progressBar.appendChild(progressBarCandy);

    progressBarContainer.appendChild(progressBar);
    return progressBarContainer;
}

function updateMessage(message, content, status) {
    const rightPart = message.querySelector('.right');
    rightPart.textContent = content;
    message.className = `message ${status}`;
}